//
//  EditMyPhoto.m
//  Bespoke
//
//  Created by Cheng on 12/9/7.
//
//

#import "EditMyPhoto.h"
#import <QuartzCore/QuartzCore.h>
#import "BK_Enviroment.h"
#import "MediaListsMedia.h"
#import "RequestAPIFunction.h"
#import "GDataXMLNode.h"
#import "LoadingUI.h"
#import "SelectBudgetCell.h"

#define LOADINGVIEW_TAG 10000000
#define LOADINGIMAGE_TAG 20000000

#define CREATED_BOOK_ID -1
#define USERUPLOAD_API @"http://54.235.166.43/BeSpokeAPI/UserUpload.php"

@implementation EditMyPhoto
@synthesize Array_AccountInfo ,ND_MyPhoto,NS_MyPhotoName,NS_PhotoType;
@synthesize Tf_Title, Bt_MyBoard,Bt_Cancel, Array_List, TVw_MyBoardList;
@synthesize Row_selected;
@synthesize delegate;

- (void)initArray:(NSMutableArray *)BoardArray {
    
    self.Array_List = [[NSMutableArray alloc] init];
    [self.Array_List addObjectsFromArray:BoardArray];
    [self.Array_List addObject:[[AccountBoard alloc] BoardID:CREATED_BOOK_ID name:@"New Book" ShareGroup:nil]];
    
    [self.TVw_MyBoardList reloadData];
}

- (IBAction)Close:(id)sender {
    
    UIAlertView *AVw_Alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"Are you sure you want to cancel?"
                                                       delegate:self
                                              cancelButtonTitle:nil
                                              otherButtonTitles:@"Yes",@"No",nil];
    AVw_Alert.cancelButtonIndex = 1;
    AVw_Alert.delegate = self;
    [AVw_Alert show];
}

- (void)OpenEditMyPhoto:(NSMutableArray *)GetUserInfo GetPhoto:(NSData *)MyPhoto GetPhotoName:(NSString *)MyPhotoName GetPhotoType:(NSString *)MyPhotoType{

    ND_MyPhoto = MyPhoto;
    NS_MyPhotoName = MyPhotoName;
    NS_PhotoType = MyPhotoType;
    
    self.backgroundColor = [UIColor clearColor];
}

-(IBAction)SelectBoard:(id)sender
{
    
    if (((AccountMyBoard *)[[Array_AccountInfo objectAtIndex:0] MyBoard]).BoardArray.count==0) {
        
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Please create a Book!" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alertView show];
        return;
    }
    
    TVw_MyBoardList.hidden = false;
    IVw_DropDownBG.hidden = false;
    
    [UIView animateWithDuration:0.2
                     animations:^{[TVw_MyBoardList setAlpha:1]; [IVw_DropDownBG setAlpha:1];}
                     completion:^(BOOL finished){ }];
    
}

- (IBAction)SavePhoto:(id)sender {
    
    BK_Enviroment *BK_User = [[BK_Enviroment alloc] init];
    
    //Get Date time now.
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"dd-MM-yyyy HH:mm"];
    NSString *NS_date = [formatter stringFromDate:[NSDate date]];
    
    NSLog(@"Current Number One = %d", [[[[Array_AccountInfo objectAtIndex:0] MyBoard] BoardArray]count]);
    AccountBoard *AB_SelectedBoard = [[[[Array_AccountInfo objectAtIndex:0] MyBoard] BoardArray] objectAtIndex:Row_selected];
    
    //Check Board name been selected.
    if ([Bt_MyBoard.titleLabel.text isEqualToString:@"     Which Book to add this to?"]) {
        
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Please select Book!" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alertView show];
         
        return;
    }
    else if ([Tf_Title.text isEqualToString:@""]) {
        
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Title is Empty!" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alertView show];
        
        return;
    }
        
    NSString *NS_MediaType;
    
    if ([NS_MyPhotoName isEqualToString:@"camera.jpg"])
        NS_MediaType = @"Camera";
    else
        NS_MediaType = @"Photo";
    
    UIImage *GetImageSetting = [UIImage imageWithData:ND_MyPhoto];
    
    //Set Loading.
    [NSThread detachNewThreadSelector:@selector(threadStartAnimating) toTarget:self withObject:nil];
    //Upload photo to server.
    NSData *responseData = [RequestAPIFunction XML_PostRequest:[NSString stringWithFormat:@"<UserPhoto UserName=\"%@\" BoardID=\"%d\"><Media ID=\"\" BeMediaID=\"\" MediaType=\"%@\" Author=\"%@\" lastUpdate=\"%@\"><Text ID=\"\" Title=\"%@\" Description=\"%@\" /><Image ID=\"\" Type=\"%@\" Width=\"%d\" Height=\"%d\" FileName=\"%@\" Description=\"\" /></Media></UserPhoto>",
                                                                BK_User.userName,
                                                                AB_SelectedBoard.BoardID,
                                                                NS_MediaType,
                                                                BK_User.userName,
                                                                NS_date,
                                                                Tf_Title.text,
                                                                TVw_PhotoContent.text,
                                                                NS_PhotoType,
                                                                (int)GetImageSetting.size.width,
                                                                (int)GetImageSetting.size.height,
                                                                NS_MyPhotoName]
                                                     urlString:USERUPLOAD_API ImageData:ND_MyPhoto];
    
    //No Network Connection or time out.
    if (responseData == nil)
        return;
    
    NSError *error;
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:responseData options:0 error:&error];
    
    //Check to upload is success.
    if ([[doc nodesForXPath:@"//Media" error:&error] count]!=0) {
        
        NSArray *Array_Media = [doc nodesForXPath:@"//Media" error:nil];
        
        //Loop into each Media Memeber
        int int_MediaID = [[[[Array_Media objectAtIndex:0] attributeForName:@"ID"] stringValue] intValue];
        NSString *NS_BeMediaID = [[[Array_Media objectAtIndex:0] attributeForName:@"BeMediaID"] stringValue];
        
        
        NSArray *TextsElements = [[Array_Media objectAtIndex:0] elementsForName:@"Text"];
        int int_TextID = [[[[TextsElements objectAtIndex:0] attributeForName:@"ID"]stringValue]intValue];
        
        
        NSArray *ImageElements = [[Array_Media objectAtIndex:0] elementsForName:@"Image"];
        int int_ImageID = [[[[ImageElements objectAtIndex:0] attributeForName:@"ID"]stringValue]intValue];
        NSString *NS_FileName = [[[ImageElements objectAtIndex:0] attributeForName:@"FileName"]stringValue];
        
        //Set Media for photo.
        MediaListsMedia *MLM_MyPhoto = [[MediaListsMedia alloc] MediaID:int_MediaID BeMediaID:NS_BeMediaID
                                                              MediaType:nil WebLink:@""
                                                                 Source:@"Photo" Author:BK_User.userName lastUpdate:NS_date];
        
        MediaListsImage *MLI_MyPhoto = [[MediaListsImage alloc] image_id:int_ImageID type:NS_PhotoType
                                                                filename:NS_FileName Width:(int)GetImageSetting.size.width
                                                                  Height:(int)GetImageSetting.size.height];
        
        MediaListsText *MLT_MyPhoto = [[MediaListsText alloc] InitialWithtext_id:int_TextID
                                                                           title:Tf_Title.text
                                                                     description:TVw_PhotoContent.text];
        
        [MLM_MyPhoto.imageArray addObject:MLI_MyPhoto];
        MLM_MyPhoto.text = MLT_MyPhoto;
        
        //Add Media to AccountMyBoard
        [((AccountBoard *)[((AccountMyBoard *)[[Array_AccountInfo objectAtIndex:0] MyBoard]).BoardArray objectAtIndex:Row_selected]).MediaArray addObject:MLM_MyPhoto];
        
        [delegate PhotoSaveSuccess:AB_SelectedBoard.name];
    }
    else if ([[doc nodesForXPath:@"//Error" error:&error] count]!=0) {
        
        NSArray *Array_Error = [doc nodesForXPath:@"//Error" error:nil];
        NSString *NS_Message = [[[Array_Error objectAtIndex:0] attributeForName:@"Message"] stringValue];
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:NS_Message delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alertView show];
    }
    else {
        
        NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:result delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alertView show];
    }
    
    [NSThread detachNewThreadSelector:@selector(threadStopAnimating) toTarget:self withObject:nil];
}

#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0)
    {
        [delegate uiViewTouched_EditMyPhoto:NO];
    }
}

#pragma mark - UITableViewDelegate

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *ButtonCellIdentifier = @"SelectBudgetCell";
    SelectBudgetCell *TVwC_SelectCell = [tableView dequeueReusableCellWithIdentifier:ButtonCellIdentifier];
    
    UIView *bgColorView = [[UIView alloc] init];
    UIColor *UC_skyblue= [UIColor colorWithRed:206.0/255.0 green:235.0/255.0 blue:236.0/255.0 alpha:1.0];
    [bgColorView setBackgroundColor:UC_skyblue];
    
    if (TVwC_SelectCell == nil) {
        
        NSArray *Array_nib = [[NSBundle mainBundle] loadNibNamed:@"SelectBudgetCell" owner:nil options:nil];
        
        TVwC_SelectCell = [Array_nib objectAtIndex:0];
        
        [TVwC_SelectCell setSelectedBackgroundView:bgColorView];
        
    }
    
    AccountBoard *Board = [self.Array_List objectAtIndex:indexPath.row];
    TVwC_SelectCell.Lab_Price.text = Board.name;
    
    if ([TVwC_SelectCell.Lab_Price.text isEqualToString:@"New Book"]) {
        TVwC_SelectCell.IVw_Symbol.hidden = NO;
        TVwC_SelectCell.Lab_Price.frame = CGRectMake(TVwC_SelectCell.IVw_Symbol.frame.origin.x+TVwC_SelectCell.IVw_Symbol.frame.size.width,
                                                     TVwC_SelectCell.frame.origin.y,
                                                     TVwC_SelectCell.frame.size.width,
                                                     TVwC_SelectCell.frame.size.height);
    }
    
    return TVwC_SelectCell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.Array_List count];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    Bt_MyBoard.titleEdgeInsets=UIEdgeInsetsMake(0, 0, 0, 0);
    [Bt_MyBoard setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
    
    AccountBoard *AB_Cell = [self.Array_List objectAtIndex:indexPath.row];
    
    [UIView animateWithDuration:0.2
                     animations:^{[tableView setAlpha:0]; [IVw_DropDownBG setAlpha:0];}
                     completion:^(BOOL finished){ }];
    
    
    if (AB_Cell.BoardID==CREATED_BOOK_ID)
        [self.delegate CreatedNewBookPressed];
    else {
        
        [Bt_MyBoard setTitle:AB_Cell.name forState:UIControlStateNormal];
        Bt_MyBoard.tag = AB_Cell.BoardID;
        Row_selected = indexPath.row;
    }
}


#pragma mark - LoadingUI

-(void)threadStartAnimating {
    
    [self.superview addSubview:[LoadingUI LoadingView:self.superview.bounds.size.width SetHeight:self.superview.bounds.size.height]];
    [self.superview addSubview:[LoadingUI LoadingImage:self.superview.bounds.size.width SetHeight:self.superview.bounds.size.height]];
}

-(void)threadStopAnimating {
    
    [[NSOperationQueue mainQueue] addOperationWithBlock:
     ^(void) {
         [[self viewWithTag:LOADINGVIEW_TAG] removeFromSuperview];
         [[self viewWithTag:LOADINGIMAGE_TAG] removeFromSuperview];
     }];
}

@end
    